package com.xprophet.crs.jpeg.codec;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import net.sourceforge.stripes.integration.spring.SpringBean;

import com.xprophet.crs.jpeg.codec.impl.SnoopDecoderImpl;
import com.xprophet.crs.jpeg.codec.impl.XDecoderImpl;
import com.xprophet.crs.jpeg.codec.model.Fingerprint;
import com.xprophet.crs.service.JPEGFingerprintService;

public class JPEGMatchManager {

	private static List<File> files = new LinkedList<File>();
	
	private static List<IJPEGDecoder> codecs = new LinkedList<IJPEGDecoder>();
	
	private static List<String> filters = new LinkedList<String>();
	
//	private static Map<String, List<Fingerprint>> matchMap = new HashMap<String, List<Fingerprint>>();
	
	@SpringBean
	private JPEGFingerprintService fpService;
	
	public JPEGMatchManager(JPEGFingerprintService service) {
		if (service != null) {
			this.fpService = service;
		}
		
		if (fpService != null) {
			List<Fingerprint> fpList = fpService.getAllFingerprintsLite();
			
			codecs.add(new XDecoderImpl(fpList));
			codecs.add(new SnoopDecoderImpl(fpList));
			
			if (fpList != null) {
				fpList.clear();
			}
		}
	}
	
	public JPEGMatchManager() {
		this(null);
	}
	
	public void scanDirectory(String dir) {
		files.clear();

		File[] fileArr = new File(dir).listFiles(new FilenameFilter() {
			public boolean accept(File dir, String name) {
				if (name.toLowerCase().endsWith(".jpg")) {
					return true;
				}
				return false;
			}
		});
		files.addAll(Arrays.asList(fileArr));
		
		for (File file : files) {
			applyCodecs(file);
		}
	}
	
	private Fingerprint applyCodecs(File jpegFile) {
		Fingerprint result = fpService.getMatchedFingerprint(codecs, filters, jpegFile);
		return result;
	}
	
	public static List<IJPEGDecoder> getCodecs() {
		return codecs;
	}

	public static List<String> getFilters() {
		return filters;
	}

	public static void main(String[] args) {
		JPEGMatchManager manager = new JPEGMatchManager();
		String dir = "C:\\Users\\fudarren\\Pictures\\wallpaper";
		manager.scanDirectory(dir);
	}
}
